<template>
	<view>
		<view class="search_center">
			<!-- 左边输入框内容开始 -->
			<view class="search_input">
				<icon type="search"></icon>
				<input placeholder="输入商品名" v-model="inputVal" @input="handleInput"></input>
			</view>
			<!-- 左边输入框内容结束 -->
			<!-- 右边按钮开始 -->
			<view class="search_btn" @tap="handleSearch">搜索</view>
			<!-- 右边按钮结束 -->
		</view>
		<!-- 搜索列表开始 -->
		<GoodsList :goods_list="goods_list" />
		<goods-list></goods-list>
		<!-- 搜索列表结束 -->
	</view>
</template>

<script>
	import GoodsList from '@/components/SearchList'
	export default {
		components:{
			GoodsList
		},
		data() {
			return {
				timer:null,
				inputVal:'',
				goods_list:[]
			};
		},
		methods:{
			// 输入框内容改变触发事件
			handleInput:function(){
				// 判断值是否为空
				if(!this.inputVal){
					uni.showToast({
						title:"输入内容不能为空",
						icon: "none"
					})
					return
				}
				if(this.timer){
					clearTimeout(this.timer)
				}
				// 解决发送空的请求的问题
				this.timer=setTimeout(()=>{
					if(!this.inputVal){
						this.goods_list=[]
					}else{
						this.getGoodsList(this.inputVal)
					}
				  this.timer=null
				},1000)
				// 用闭包的方法解决发送空的请求的问题
				// let _this=this;
				// (function(inputVal){
				// 	_this.timer=setTimeout(()=>{
				// 		_this.getGoodsList(inputVal)
				// 		 _this.timer=null
				// 	},1000)
				// })(this.inputVal)
			},
			// 搜索商品的接口和数据
			getGoodsList:async function(inputVal){
				const res=await this.$request({
					url:'goods/qsearch',
					data:{
						query: inputVal
					}
				})
				console.log(res)
				if(res.message.length===0){
					uni.showToast({
						title:"暂无数据",
						icon:'none'
					})
				}
				this.goods_list=res.message
			},
			// 搜索按钮点击事件
			handleSearch:function(){
				if(!this.inputVal){
					uni.showToast({
						title:"搜索内容不能为空",
						icon: "none"
					})
					return
				}
				this.getGoodsList(this.inputVal)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.search_center {
		margin-bottom: 15rpx;
	}

	.search_center .search_input {
		margin-top: 15rpx;
		margin-left: 18rpx;
		width: 599rpx;
		height: 61rpx;
		border-radius: 27rpx;
		display: flex;
		align-items: center;
		background-color: #e7e7e7;
		float: left;
	}

	.search_center .search_btn {
		float: left;
		width: 101rpx;
		height: 61rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #EA4350;
		border-radius: 8rpx;
		margin-top: 15rpx;
		margin-left: 15rpx;
		color: white;
		font-size: 25rpx;
	}
</style>

